package com.gitee.advice;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gitee.base.Result;
import com.gitee.constants.ResponseKey;
import com.gitee.constants.ResultStatusCode;
import com.gitee.exception.BaseException;

/**
 * 控制器异常拦截增强器
 *  
 * @author  赵炎
 * @version  [V1.00, 2019年1月25日]
 * @since V1.00
 */
@ControllerAdvice
public class ControllerExceptionHandler
{
    private static final Logger LOG = LoggerFactory.getLogger(ControllerExceptionHandler.class);
    
    /** 
     * 全局异常处理
     * @param BusinessException ex 
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result exceptionHanler(Exception ex)
    {
        LOG.error(" an error occurs from the request.", ex);
        Result result = new Result();
        result.put(ResponseKey.TIMESTAMP, System.currentTimeMillis());
        result.put(ResponseKey.CODE, ResultStatusCode.INNER_ERROR);
        result.put(ResponseKey.MESSAGE, ex.getMessage());
        return result;
    }
    
    /** 
     * 自定义异常处理
     * @param BaseException ex 
     * @return
     */
    @ExceptionHandler(value = BaseException.class)
    @ResponseBody
    public Result exceptionHanler(BaseException ex)
    {
        LOG.error(" a base exception occurs from the request.", ex);
        Result result = new Result();
        // handler处理
        ex.handler(result);
        return result;
    }
}
